package com.gxs.waqas.localfolders.utils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

public class ChecksumCalculator {

  public static void main(String [] args)
  {
	  try
	  {
		  //doCheckSumTest("S:\\Pictures and Videos\\ORGANIZED_CAMERA_PICTURES\\2013-06-01-SalmasIPhone\\001_IMG_1113.jpg");
			String checksumFile = "S:\\checksums.csv";
			String location = "S:\\Pictures and Videos\\_allOtherFolders\\PicsFromBlackLaptop-ProbablyAllOnFlickr";
			String deletedLocation = "S:\\Pictures and Videos\\_deleted";
			String masterLocation  = "S:\\Pictures and Videos\\ORGANIZED_CAMERA_PICTURES";
		  ChecksumLoader loader = new ChecksumLoader();
		  loader.loadChecksumsIntoMaps(checksumFile);
		  computeCheckSumsForAllFiles(masterLocation, loader);
	  }
	  catch(Exception e)
	  {
		  e.printStackTrace();
	  }
  }

  public static void doCheckSumTest(String fileName) throws Exception
  {
	  long time = 0;
	  time = System.currentTimeMillis();
	  String checkSum = getCheckSumOfFile(fileName);
	  time = System.currentTimeMillis() - time;
	  System.out.println("checksum: "  + checkSum + " for file: " + fileName + ", took: " + time + " milliseconds");
  }
  public static String getCheckSumOfFile(String fileName) throws IOException, NoSuchAlgorithmException
  {
	  	MessageDigest md = MessageDigest.getInstance("SHA1");
	  	FileInputStream fis = new FileInputStream(fileName);
	    byte[] dataBytes = new byte[1024];
	 
	    int nread = 0; 
	 
	    while ((nread = fis.read(dataBytes)) != -1) {
	      md.update(dataBytes, 0, nread);
	    };
	 
	    byte[] mdbytes = md.digest();
	 
	    //convert the byte to hex format
	    StringBuffer sb = new StringBuffer("");
	    for (int i = 0; i < mdbytes.length; i++) {
	    	sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
	    }
	 
	    // close the stream
	    fis.close();
	   return sb.toString();
	 
  }
  
  public static void computeCheckSumsForAllFiles(String startingLocation, ChecksumLoader loader) throws Exception
  {
	  File location = new File(startingLocation);
	  
	  File[] potentialFolders = location.listFiles();
	  
	  List<String> listOfResults = new ArrayList<String>();
	  
	  for(int i=0; i<potentialFolders.length; i++)
	  {
		  File currentFolder = potentialFolders[i];
		  
		  if(currentFolder.isDirectory())
		  {
			  File [] listOfFiles = currentFolder.listFiles();
			  
			  if(listOfFiles == null)
				  continue;
			  
			  for(int j=0; j< listOfFiles.length; j++)

			  {
				  File currentFile = listOfFiles[j];
				  if(currentFile.isFile())
				  {
					  System.out.println("Processing Folder " + (i+1) + " of " + potentialFolders.length +  ", file " + (j+1) + " of " +listOfFiles.length + ", File: " + currentFile.getName() + ", location: " + currentFile.getParent());
					  if(loader.mapOfFilesByAbsoluatePath.get(currentFile.getAbsolutePath()) == null)
					  {
					  
						  String checksum = getCheckSumOfFile(currentFile.getAbsolutePath());
						  List<String> elements = new ArrayList<String>();
						  elements.add(currentFile.getParentFile().getName() + "\\" + currentFile.getName());
						  elements.add(currentFile.getName());
						  elements.add(currentFile.getAbsolutePath());
						  elements.add(checksum);
						  elements.add(String.valueOf(currentFile.lastModified()) );
						  String result = printElements(elements);
						  listOfResults.add(result);
					  }
				  }
			  }
		  }
	  }
	  
	  FileWriter fw = new FileWriter(new File("S:\\checksums.csv"), true);
	  BufferedWriter writer = new BufferedWriter(fw);
	  
	  for(String line : listOfResults)
	  {
		  writer.write(line + "\n");
	  }
	  
	  writer.flush();
	  writer.close();
	  fw.close();

	  
	  //
	  // Now print the results to a csv file. 
  }
  
  public static String printElements(List<String> elements)
  {
	  String result = "";
	  for(String key : elements)
	  {
		  result = result + "\"" + key + "\",";
	  }

	  return result;
  }

}
